#pragma once
#include<iostream>
#include<time.h>
#include<unistd.h>
#include<stdarg.h>
#include<fstream>
#include<string.h>
#include"lockguard.hpp"
using namespace std;
#define SCREENSTATUS 1
#define FILESTATUS 2
string _filename = "./log.txt";
int status = 1;
pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER;
#define ENABLESCREEN() do{status =1;}while(0)
#define ENABLEFILE(Filename) do{status =2;_filename =Filename;}while(0)
#define LOG(Level,Format,...) do{log(__FILE__,__LINE__,Level,Format,##__VA_ARGS__);}while(0)
enum
{
	DEBUG =1,
	INFO,
	WARNING,
	ERROR,
	FATAL

};
const string LevelToString(int level)
{
	switch(level)
	{
		case DEBUG: return "DEBUG";
		case INFO: return "INFO";
		case WARNING: return "WARNING";
		case ERROR: return "ERROR";
		case FATAL: return "FATAL";
		default: return "UNKNOW";
	};
};
const string GetTime()
{
	time_t now=time(nullptr);
	struct tm* cur_time =localtime(&now);
	char buffer[128];
	snprintf(buffer,sizeof(buffer),"%d-%02d-%02d %02d:%02d:%2d",
			cur_time->tm_year+1900,
			cur_time->tm_mon+1,
			cur_time->tm_mday,
			cur_time->tm_hour,
			cur_time->tm_min,
			cur_time->tm_sec
			);
	return static_cast<const string>(buffer);
};
void log(const string& filename,int fileline,int level,const char* format,...)
{
	va_list ap;
	va_start(ap,format);
	char log_info[1024];
	vsnprintf(log_info,sizeof(log_info),format,ap);
	va_end(ap);
	lockguard lg(&glock);
	if(status==1)
	{
		printf("[%s][%d][%s][%d][%s] %s\n",
			LevelToString(level).c_str(),
			getpid(),
			filename.c_str(),
			fileline,
			GetTime().c_str(),
			log_info);

	}
	else if(status==2)
	{

		ofstream out(_filename,ios::app);//追加性写
		if(!out.is_open())
			return;
		char logtxt[2048];
		snprintf(logtxt,sizeof(logtxt),"[%s][%d][%s][%d][%s] %s\n",
			LevelToString(level).c_str(),
			getpid(),
			filename.c_str(),
			fileline,
			GetTime().c_str(),
			log_info);
		out.write(logtxt,strlen(logtxt));
		out.close();

	};
};
